use axum::body::Body;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
use axum::response::Response;
use crate::redis::*;

pub async fn auth_filter(request: Request<Body>, next: Next) -> Result<Response, StatusCode> {
    // 获取当前的url
    let uri = request.uri();

    tracing::info!("uri: {}", uri);

    if uri.eq("/login") {
        return Ok(next.run(request).await)
    };

    if let Some(token) = request.headers().get("Authorization") {
        tracing::info!("token: {:?}", token);
        let token = String::from(token.to_str().map_err(|_| StatusCode::UNAUTHORIZED)?);

        if !token.starts_with("Bearer ") {
            return Err(StatusCode::UNAUTHORIZED);
        }

        let token = token.strip_prefix("Bearer ").unwrap();
        // redis获取是否登录
        let code = get_string(token).await;
        match code {
            Ok(code) => {
                if code == "" {
                    return Err(StatusCode::UNAUTHORIZED)
                }
            },
            Err(_) => return Err(StatusCode::UNAUTHORIZED)
        }

    } else {
        return Err(StatusCode::FORBIDDEN);
    }

    Ok(next.run(request).await)
}